package com.baiyun.controller;

import cn.hutool.core.map.MapUtil;
import com.baiyun.common.Constants;
import com.baiyun.common.Result;
import com.baiyun.domain.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.security.Principal;
import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/sys/menu")
public class MenuController extends BaseController{
    /**
     * 用户当前用户的菜单和权限信息
     * @param principal
     * @return
     */
    @GetMapping("/nav")
    public Result nav(Principal principal) {
        User user = userService.getByUsername(principal.getName());
        // 获取权限信息 ROLE_admin,ROLE_normal,sys:user:list,....
        String authority = userService.getUserAuthority(user.getId());
        String[] authorityArray = StringUtils.tokenizeToStringArray(authority, ",");
        // 获取导航栏信息
        List<MenuDTO> navs = menuService.getCurrentUserNav();
        return Result.success(MapUtil.builder()
                .put("authoritys", authorityArray)
                .put("nav", navs)
                .map()
        );
    }

    @GetMapping("/info/{id}")
    @PreAuthorize("hasAuthority('sys:menu:list')")
    public Result info(@PathVariable(name = "id") Long id){
        return Result.success(menuService.getById(id));
    }

    @GetMapping("list")
    @PreAuthorize("hasAuthority('sys:menu:list')")
    public Result list(){
        List<Menu> menus = menuService.tree();
        return Result.success(menus);
    }

    @PostMapping("/save")
    @PreAuthorize("hasAuthority('sys:menu:save')")
    public Result save(@Valid @RequestBody Menu menu){
        menu.setCreated(LocalDateTime.now());
        menuService.save(menu);
        return Result.success(menu);
    }

    @PostMapping("/update")
    @PreAuthorize("hasAuthority('sys:menu:update')")
    public Result update(@Valid @RequestBody Menu menu){
        menu.setUpdated(LocalDateTime.now());
        menuService.updateById(menu);
        //清除所有与该菜单相关的权限缓存
        userService.clearUserAuthorityByMenuId(menu.getId());
        return Result.success(menu);
    }

    @PostMapping("/delete/{id}")
    @PreAuthorize("hasAuthority('sys:menu:delete')")
    public Result delete(@PathVariable("id") Long id){
        long count = menuService.count(new QueryWrapper<Menu>().eq("parent_id", id));
        if (count > 0){
            return Result.error(Constants.CODE_400,"请先删除子菜单");
        }
        //清除菜单缓存
        userService.clearUserAuthorityByMenuId(id);
        //清除有关中间表
        roleMenuService.remove(new QueryWrapper<RoleMenu>().eq("menu_id",id));
        return Result.success();
    }

    /**
     * 查询图标
     * @return
     */
    @GetMapping("/icons")
    public Result icons(){
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("type", Constants.DICT_TYPE_ICON);
        return Result.success(dictMapper.selectList(queryWrapper));
    }
}
